import datetime
import decimal

from sqlalchemy import text

from py.PojosAndDaos.Account import Account_class
from py.PojosAndDaos.Book import Book_class
from py.PojosAndDaos.Record import Record_class
from py.PojosAndDaos.Job import Job_class


class LendService:
    # 借书功能
    @classmethod
    def LendBooks(cls, account: Account_class(), book: Book_class(), amount):
        session1 = Account_class().session
        session2 = Book_class().session
        session3 = Record_class().session
        session4 = Job_class().session
        if account.Debt > 0:
            return "您尚有欠款未还清"
        elif account.number + amount > session4.query(Job_class()).filter_by(job=account.job).one_or_none().constrain:
            return "书目数量已达上限！"
        elif book.left < amount:
            return "书目不足！"
        else:
            DateAndTime = datetime.datetime.now()
            session3.execute(
                text("INSERT INTO LENDLISTTABLE (READERID, ISBN, BOOKNAME, LENDNUM, LENDDATE, ISRETURNED ,ISLOST) "
                     "VALUES ('{}','{}','{}','{}','{}',FALSE,FALSE)".
                     format(account.ReaderID, book.ISBN, book.name, amount, DateAndTime)))
            session3.commit()
            session3.close()
            book = session2.query(Book_class()).filter_by(ISBN=book.ISBN).one_or_none()
            book.left = book.left - amount
            book.count = book.count + amount
            session2.commit()
            session2.close()
            session1.execute(text("UPDATE READERTABLE SET READERTABLE.NUMBER = '{}' WHERE READERID = '{}'".
                                  format(account.number + amount, account.ReaderID)))
            session1.commit()
            session1.close()
            return "借阅成功！"

    # 还书功能
    @classmethod
    def ReturnBook(cls, record: Record_class(), x: int):
        session1 = Account_class().session
        session2 = Book_class().session
        session3 = Record_class().session
        account = session1.query(Account_class()).filter_by(ReaderID=record.ReaderID).one_or_none()
        book = session2.query(Book_class()).filter_by(ISBN=record.ISBN).one_or_none()
        record = session3.query(Record_class()).filter_by(ReaderID=record.ReaderID, ISBN=record.ISBN,
                                                          isReturned=False, isLost=False).first()
        if account is None or book is None or record is None:
            return '给的ReaderID或ISBN不正确或不存在'

        account.number = account.number - record.lendNum
        book.left = book.left + record.lendNum
        session1.commit()
        session2.commit()

        record.ReturnDate = datetime.datetime.now()
        if x == 1:
            LendService.CalculateDebt(record)
        record.isReturned = True
        session3.commit()
        session3.close()
        return "还书成功！"

    # 申报书籍丢失
    @classmethod
    def ReportLossOfBooks(cls, record: Record_class()):
        session1 = Account_class().session
        session2 = Book_class().session
        session3 = Record_class().session
        account = session1.query(Account_class()).filter_by(ReaderID=record.ReaderID).one_or_none()
        book = session2.query(Book_class()).filter_by(ISBN=record.ISBN).one_or_none()
        record = session3.query(Record_class()).filter_by(ReaderID=record.ReaderID, ISBN=record.ISBN,
                                                          isLost=False).first()
        if account is None or book is None or record is None :
            return '给的ReaderID或ISBN不正确或不存在'

        account.number = account.number - record.lendNum
        record.isLost = True
        account.Debt = record.lendNum * book.price

        session1.commit()
        session2.commit()
        session3.commit()
        session3.close()
        return "申报成功！"

    # 计算欠款
    @classmethod
    def CalculateDebt(cls, record: Record_class()):
        session1 = Account_class().session
        session2 = Book_class().session
        account = session1.query(Account_class()).filter_by(ReaderID=record.ReaderID).one_or_none()
        book = session2.query(Book_class()).filter_by(ISBN=record.ISBN).one_or_none()
        start = record.LendDate
        end = record.ReturnDate
        time = (end - start).days
        debt = book.price * record.lendNum
        if time <= 20:
            pass
        elif 20 < time <= 60:
            account.Debt = account.Debt + decimal.Decimal(debt * 0.1)
        elif 60 < time <= 90:
            account.Debt = account.Debt + decimal.Decimal(debt * 0.3)
        else:
            account.Debt = account.Debt + decimal.Decimal(debt * 0.5)
        session1.commit()
        return "对该借阅记录的欠款计算完成"

    @classmethod
    def Debt_Clear(cls, readerID: int, fee: float):
        session1 = Account_class().session
        account = session1.query(Account_class()).filter_by(ReaderID=readerID).first()
        if account is None:
            return 'readerID不存在'
        if account.Debt >= decimal.Decimal.from_float(fee):
            account.Debt = account.Debt - decimal.Decimal.from_float(fee)
        else:
            return '给钱太多了，没欠费这么多，我不能要'
        session1.commit()
        session1.close()
        return "缴费成功"


if __name__ == '__main__':
    account = Account_class().session.query(Account_class()).filter_by(ReaderID=1).one_or_none()
    print(account.__dict__)
    book = Book_class().session.query(Book_class()).filter_by(ISBN="9787040561456").one_or_none()
    print(book.__dict__)
    LendService.LendBooks(account, book, 2)
